<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 作品列表 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.key" placeholder="关键字搜索" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="contestantinfo.author" width="140" label="作者"></el-table-column>
                <el-table-column prop="contestantinfo.phone" width="150" label="联系方式"></el-table-column>
                <el-table-column prop="contestantinfo.idCard" width="170" label="身份证号码"></el-table-column>
                <el-table-column prop="contestantinfo.school" label="职业" width="200"></el-table-column>
                <!-- <el-table-column prop="count" label="投票数" width="80"></el-table-column> -->
                <el-table-column label="创建时间" width="200">
                    <template slot-scope="scope">
                        {{ scope.row.create_time | formatDate() }}
                    </template>
                </el-table-column>
                <el-table-column label="审核状态" width="110">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.audit == '1' ? 'success' : scope.row.audit == '2' ? 'danger' : ''">
                            {{ scope.row.audit == 0 ? '未审核' : '' }}
                            {{ scope.row.audit == 1 ? '审核通过' : '' }}
                            {{ scope.row.audit == 2 ? '审核不通过' : '' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="审核时间" width="200">
                    <template slot-scope="scope">
                        {{ scope.row.audit_time | formatDate() }}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="300" align="center">
                    <template slot-scope="scope">
                        <a class="el-button--text font-28 curcon"  style="margin-right: 10px" @click="ajaxDown(scope.row.video)"
                            >下载视频</a
                        >
                         <a class="el-button--text font-28 curcon" style="margin-right: 10px" @click="viewDetail(scope)">详情</a>
                        <el-button type="text" @click="handleEdit(scope.$index, scope.row)">审核通过</el-button>
                        <el-button type="text" class="red" @click="handleEdit1(scope.$index, scope.row)">审核不通过</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog v-dialogDrag title="作品详情" center :visible.sync="visible" width="80%" height="80%">
            <div style="margin: auto; width: 70%">
                <video v-if="visible" controls poster="./../../assets/img/index_top_bg.png" width="100%">
                    <source :src="`http://${videosource}`" type="video/mp4" />
                </video>
            </div>
            <div style="margin: auto; width: 70%">
                <div class="detail">
                    <div class="detail1">作者:</div>
                    <div class="detail2">{{ detailInfo.author }}</div>
                </div>
                <div class="detail">
                    <div class="detail1">联系方法:</div>
                    <div class="detail2">{{ detailInfo.phone }}</div>
                </div>
                <div class="detail">
                    <div class="detail1">学校:</div>
                    <div class="detail2">{{ detailInfo.school }}</div>
                </div>
                <div class="detail">
                    <div class="detail1">投票数:</div>
                    <div class="detail2">{{ detailInfo.count }}</div>
                </div>
                <div class="detail">
                    <div class="detail1">审核状态:</div>
                    <div class="detail2">{{ detailInfo.audit }}</div>
                </div>
                <div class="detail">
                    <div class="detail1">审核时间:</div>
                    <div class="detail2">{{ detailInfo.audit_time | timeFormat() }}</div>
                </div>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="visible = false">关 闭</el-button>
                <el-button type="primary" @click="buttonSubmit(1)">审核通过</el-button>
                <el-button type="danger" @click="buttonSubmit(2)">审核不通过</el-button>
                <el-button type="primary">
                    <a class="font-28 curcon"  style="color: white" @click="ajaxDown(videosource)">下载视频</a>
                </el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { fetchData } from '../../api/index';
import { formatDate } from '@/utils/tool';
import {
	API_URL,
} from '../../../env.js'
import downloadByUrl from 'downloadbyurl';
export default {
    name: 'basetable',
    filters: {
        timeFormat(val) {
            return val ? formatDate(val) : '';
        }
    },
    data() {
        return {
            query: {
                key: '',
                pageIndex: 1,
                pageSize: 10
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            visible: false,
            videosource: '',
            detailInfo: {
                author: '',
                phone: '',
                school: '',
                count: '',
                audit: '',
                id: '',
                audit_time: ''
            }
        };
    },
    created() {
        this.getData();
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        getData() {
            // fetchData(this.query).then(res => {
            //     console.log(res);
            //     this.tableData = res.list;
            //     this.pageTotal = res.pageTotal || 50;
            // });
            let ajaxData = {
                pageIndex: this.query.pageIndex,
                pageSize: 10
            };
            if (this.query.key) {
                ajaxData['key'] = this.query.key;
            }
            this.http
                .get('/admin/works', ajaxData)
                .then((res) => {
                    console.log(res);
                    this.tableData = res.data.rows;
                    this.pageTotal = res.data.count;
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        ajaxDown(url) {
            let fileExtension = url.substring(url.lastIndexOf('.') + 1);
            let _url = `${API_URL}/home/download?url=https://${url}`;
            var a = document.createElement('a');
            a.href = _url;
            a.download = +new Date() + '.' + fileExtension;
            document.body.appendChild(a);
            a.click();
        },
        downloadWithBlob(url, fileName) {
            if (url) {
                var userAgent = navigator.userAgent;
                console.log(userAgent);
                if (!!window.ActiveXObject || 'ActiveXObject' in window) {
                    window.location.href = url;
                    return;
                }
                try {
                    var eleLink = document.createElement('a');
                    eleLink.download = fileName || '文件';
                    eleLink.style.display = 'none';
                    eleLink.href = url;
                    // 触发点击
                    document.body.appendChild(eleLink);
                    eleLink.click();
                    document.body.removeChild(eleLink);
                } catch (e) {}
            } else {
                layer.msg('下载失败');
            }
        },
        getDownLoad(url) {
            this.http
                .get('/home/download', {
                    url
                })
                .then((res) => {
                    console.log('res', res);
                });
        },
        fetcheDown(url) {
            let fileExtension = url.substring(url.lastIndexOf('.') + 1);
            var x = new XMLHttpRequest();
            x.open('GET', url, true);
            x.responseType = 'blob';
            x.onload = function (e) {
                //会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
                var _url = window.URL.createObjectURL(x.response);
                var a = document.createElement('a');
                a.href = _url;
                a.download = +new Date() + '.' + fileExtension;
                document.body.appendChild(a);
                a.click();
            };
            x.send();
        },
        viewDetail(item) {
            console.log(item);
            this.visible = true;
            this.videosource = item.row.video;
            this.detailInfo.author = item.row.contestantinfo.author;
            this.detailInfo.phone = item.row.contestantinfo.phone;
            this.detailInfo.school = item.row.contestantinfo.school;
            this.detailInfo.count = item.row.count;
            this.detailInfo.id = item.row.id;
            this.detailInfo.audit_time = item.row.audit_time;
            if (item.row.audit == 0) {
                this.detailInfo.audit = '未审核';
            }
            if (item.row.audit == 1) {
                this.detailInfo.audit = '审核通过';
            }
            if (item.row.audit == 2) {
                this.detailInfo.audit = '审核不通过';
            }
        },
        // 无闪现下载excel
        download(urltmp) {
            if (!urltmp) return;
            var Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
            var objExp = new RegExp(Expression);
            let url = urltmp;
            if (!objExp.test(urltmp)) {
                url = `https://${urltmp}`;
            }
            const iframe = document.createElement('iframe');
            iframe.style.display = 'none';
            function iframeLoad() {
                console.log('iframe onload');
                const win = iframe.contentWindow;
                const doc = win.document;
                if (win.location.href === url) {
                    if (doc.body.childNodes.length > 0) {
                        // response is error
                    }
                    iframe.parentNode.removeChild(iframe);
                }
            }
            if ('onload' in iframe) {
                iframe.onload = iframeLoad;
            } else if (iframe.attachEvent) {
                iframe.attachEvent('onload', iframeLoad);
            } else {
                iframe.onreadystatechange = function onreadystatechange() {
                    if (iframe.readyState === 'complete') {
                        iframeLoad;
                    }
                };
            }
            iframe.src = '';
            document.body.appendChild(iframe);

            setTimeout(function loadUrl() {
                iframe.contentWindow.location.href = url;
            }, 50);
        },

        downloadFile(url) {
            downloadByUrl(url);
        },

        buttonSubmit(audit) {
            console.log(audit);
            let ajaxData = {
                id: '' + this.detailInfo.id,
                audit: audit
            };
            this.http
                .post('/admin/audit', ajaxData)
                .then((res) => {
                    console.log(res);
                    this.visible = false;
                    this.$message.success(`审核成功`);
                    this.getData();
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定审核不通过吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    console.log(row);
                    let ajaxData = {
                        id: '' + row.id,
                        audit: 2
                    };
                    this.http
                        .post('/admin/audit', ajaxData)
                        .then((res) => {
                            console.log(res);
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                    this.getData();
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        // 编辑操作
        handleEdit(index, row) {
            console.log(row);
            let ajaxData = {
                id: '' + row.id,
                audit: 1
            };
            this.http
                .post('/admin/audit', ajaxData)
                .then((res) => {
                    console.log(res);
                })
                .catch((err) => {
                    console.log(err);
                });
            this.getData();
            // this.idx = index;
            // this.form = row;
            // this.editVisible = true;
        },
        handleEdit1(index, row) {
            console.log(row);
            let ajaxData = {
                id: '' + row.id,
                audit: 2
            };
            this.http
                .post('/admin/audit', ajaxData)
                .then((res) => {
                    console.log(res);
                })
                .catch((err) => {
                    console.log(err);
                });
            this.getData();
            // this.idx = index;
            // this.form = row;
            // this.editVisible = true;
        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;
            this.$message.success(`修改第 ${this.idx + 1} 行成功`);
            this.$set(this.tableData, this.idx, this.form);
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.el-button span {
    margin-left: 0 !important;
}
.detail {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    align-content: center;
    justify-content: flex-start;
    align-items: center;
    line-height: 34px;
    font-size: 16px;
}
.detail1 {
    text-align: right;
    margin-right: 15px;
    width: 80px;
    color: #999;
}
.detail2 {
    width: 230px;
}
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.font-28 {
    font-size: 12px;
}
.curcon{
    cursor:pointer
}
</style>
